import {
    getDocRoots,
    parseSingleDoc,
    unzipOfd
} from "./ofd_parser";
import {pipeline} from "./pipeline";
import {calPageBox, calPageBoxScale, renderPage} from "./ofd_render";
import {getPageScal, setPageScal} from "./ofd_util";
export const parseOfdDocument = function (options) {
    if (options.ofd instanceof File || options.ofd instanceof ArrayBuffer) {
        doParseOFD(options);
    } else {
        // JSZipUtils.getBinaryContent(options.ofd, function (err, data) {
        //     if (err) {
        //         if (options.fail) {
        //             options.fail(err);
        //         }
        //     } else {
        //         options.ofd = data;
        //         doParseOFD(options);
        //     }
        // });
    }
}

const doParseOFD = function (options) {
    window.global.xmlParseFlag = 0;
    pipeline.call(this, async () => await unzipOfd(options.ofd), getDocRoots, parseSingleDoc)
    .then(res => {
        if (options.success) {
            options.success(res);
        }
    })
    .catch(res => {
        console.log(res)
        if (options.fail) {
            options.fail(res);
        }
    });
}

export const renderOfd = function (screenWidth, ofd) {
    let divArray = [];
    if (!ofd) {
        return divArray;
    }
    for (const page of ofd.pages) {
        let box = calPageBox(screenWidth, ofd.document, page);
        const pageId = Object.keys(page)[0];
        let pageDiv = document.createElement('div');
        pageDiv.id = pageId;
        pageDiv.setAttribute('style', `margin-bottom: 20px;position: relative;width:${box.w}px;height:${box.h}px;background: white;`)
        renderPage(pageDiv, page, ofd.tpls, ofd.fontResObj, ofd.drawParamResObj, ofd.multiMediaResObj);
        divArray.push(pageDiv);
    }
    return divArray;
}